//
// Created by 33145 on 2023/5/28.
//

#ifndef ROCKET_FDEVENT_H
#define ROCKET_FDEVENT_H

#include <functional>
#include <sys/epoll.h>
#include <memory>

namespace rocket {
  class FdEvent {
  public:
    typedef std::shared_ptr<FdEvent> ptr;
    enum TriggerEvent {
      IN_EVENT = EPOLLIN,
      OUT_EVENT = EPOLLOUT,
      ERROR_EVENT = EPOLLERR,
    };

    explicit FdEvent(int fd);
    FdEvent();
    ~FdEvent() = default;
    void setNonBlock();
    std::function<void()> handler(TriggerEvent event_type);
    void listen(TriggerEvent event_type, std::function<void()> callback, std::function<void()> error_callback = nullptr);
    void cancel(TriggerEvent event_type);
    int getFd() const;
    epoll_event getEpollEvent();

  protected:
    int _fd {-1};

    epoll_event _listen_events;

    std::function<void()> _read_callback {nullptr};
    std::function<void()> _write_callback {nullptr};
    std::function<void()> _error_callback {nullptr};
  };
}


#endif //ROCKET_FDEVENT_H
